import React, { useState,useEffect } from "react";
import "./style.less";
import { withRouter,useParams } from "react-router-dom";
import { useSelector, useDispatch } from "react-redux";
import { updateSearch } from "../../redux/actions/search";

function SearchInput(props) {
  const [value, setValue] = useState("");
  const dispatch = useDispatch();
  const search = useSelector((state) => state.search);
  const {keyword} = useParams()

  useEffect(() => {
    setValue(search)
    if(keyword) {
      dispatch(updateSearch(keyword))
    } else {
      dispatch(updateSearch(''))
    }
  },[search,keyword]) // eslint-disable-line

  function keyHandle(e) {
    const { keyCode } = e;
    if (keyCode === 13 && value.length !== 0) {
      props.history.push(`/search/${value}`);
      dispatch(updateSearch(value));
    }
  }

  function changeValue(e) {
    setValue(e.target.value);
  }

  return (
    <input
      type="text"
      className="search-input"
      value={value}
      onChange={changeValue}
      onKeyUp={keyHandle}
    />
  );
}

export default withRouter(SearchInput);
